package com.kakahair.common.util.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.lang.reflect.Array;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by sang on 17-1-16.
 */

public abstract class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {

	private Class<T> clazz;

	public ListTypeHandler(Class<T> clazz) {
		this.clazz = clazz;
	}
	
	@Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<T> ts, JdbcType jdbcType) throws SQLException {
        StringBuffer result = new StringBuffer();
        for (T value : ts) {
            result.append(value).append(",");
        }
        result.deleteCharAt(result.length() - 1);
        ps.setString(i, result.toString());
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return toList(resultSet.getString(columnName));
    }

    @Override
    public List<T> getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return toList(resultSet.getString(columnIndex));
    }

    @Override
    public List<T> getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return toList(callableStatement.getString(columnIndex));
    }

	List<T> toList(String columnValue) {
		if (columnValue == null) {
			return new ArrayList<T>();
		}
		String[] values = columnValue.split(",");
		List<T> array = new ArrayList<T>();
		for (int i = 0; i < values.length; i++) {
			array.add(parseString(values[i]));
		}
		return array;
	}

	abstract T parseString(String string);
}